<template>
  <div class="department-selection">
    <div class="page-header">
      <h2>选择挂号科室</h2>
    </div>

    <div class="search-box">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入科室名称搜索"
        prefix-icon="Search"
        clearable
        @input="handleSearch"
        size="large"
      />
    </div>

    <div class="date-info">
      <el-tag type="info" size="large">
        <el-icon><Calendar /></el-icon>
        今天是 {{ currentDate }}
      </el-tag>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="6" animated />
    </div>

    <div v-else-if="departments.length === 0" class="empty-state">
      <el-empty description="今日暂无科室排班" />
    </div>

    <div v-else class="department-buttons">
      <div
        class="button-row"
        v-for="(row, rowIndex) in buttonRows"
        :key="rowIndex"
      >
        <el-button
          v-for="department in row"
          :key="department.department_id"
          class="department-button"
          @click="selectDepartment(department)"
          :disabled="department.doctorCount === 0"
        >
          <div class="button-content">
            <el-icon class="button-icon"><OfficeBuilding /></el-icon>
            <div class="button-text">
              <div class="department-name">
                {{ department.department_name }}
              </div>
              <div class="department-location">
                {{ department.department_location }}
              </div>
              <div class="department-status">
                <span class="waiting"
                  >医生: {{ department.doctorCount }} 人</span
                >                
              </div>
            </div>
          </div>
        </el-button>
      </div>
    </div>

    <div class="pagination-controls" v-if="totalPages > 1">
      <el-button
        class="page-button"
        :disabled="currentPage === 1"
        @click="currentPage--"
      >
        上一页
      </el-button>
      <div class="page-indicator">
        第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
      </div>
      <el-button
        class="page-button"
        :disabled="currentPage === totalPages"
        @click="currentPage++"
      >
        下一页
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, shallowRef } from "vue";
import { ElMessage } from "element-plus";
import { OfficeBuilding, Search, Calendar } from "@element-plus/icons-vue";

// 引入API接口
import { getScheduleInstancesDataByCurrentDate } from "@/api/api";

const props = defineProps({
  // 可以添加需要的props
});

const emit = defineEmits(['department-selected']);

const searchKeyword = ref("");
const currentPage = ref(1);
const pageSize = ref(8);
const loading = ref(true);
const currentDate = ref("");

// 从数据库获取的科室数据
const departments = shallowRef([]);


// 格式化日期显示
const formatDate = (date) => {
  const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const weekday = weekdays[date.getDay()];
  return `${month}月${day}日 ${weekday}`;
};

// 统计科室医生数量
const countDoctorsByDepartment = (scheduleData) => {
  const departmentMap = new Map();
  
  // 遍历排班数据，按科室分组统计医生数量
  scheduleData.forEach(schedule => {
    const deptId = schedule.department_id;
    const doctorId = schedule.staff_id;
    
    if (!departmentMap.has(deptId)) {
      // 如果是新的科室，初始化数据
      departmentMap.set(deptId, {
        department_id: deptId,
        department_name: schedule.department_name,
        department_location: schedule.department_location,
        doctorIds: new Set(), // 使用Set来去重医生ID
        schedules: []
      });
    }
    
    const department = departmentMap.get(deptId);
    // 添加医生ID到Set中（自动去重）
    department.doctorIds.add(doctorId);
    // 添加排班数据
    department.schedules.push(schedule);
  });
  
  // 转换为数组格式并计算医生数量
  return Array.from(departmentMap.values()).map(dept => ({
    ...dept,
    doctorCount: dept.doctorIds.size,
    // 不需要保留doctorIds集合，转换为数组如果需要的话
    doctorIds: Array.from(dept.doctorIds)
  }));
};

// 获取排班数据
const fetchScheduleData = async () => {
  try {
    loading.value = true;
    currentDate.value = formatDate(new Date());

    // 这里是实际的API调用
    const response = await getScheduleInstancesDataByCurrentDate();

    // console.log(response.data);

    if (response && response.code == 200) {
      // 使用统计函数处理排班数据
      const processedDepartments = countDoctorsByDepartment(response.data);
      departments.value = processedDepartments;
      
      // console.log('处理后的科室数据:', processedDepartments);
    } else {
      departments.value = [];
    }
  } catch (error) {
    console.error("获取排班数据失败:", error);
    ElMessage.error("获取科室信息失败，请稍后重试");
    departments.value = [];
  } finally {
    loading.value = false;
  }
};

// 过滤后的科室列表
const filteredDepartments = computed(() => {
  if (!searchKeyword.value) return departments.value;
  const keyword = searchKeyword.value.toLowerCase();
  return departments.value.filter(
    (dept) =>
      dept.department_name.toLowerCase().includes(keyword) ||
      dept.department_location.toLowerCase().includes(keyword)
  );
});

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredDepartments.value.length / pageSize.value);
});

// 分页后的科室数据
const pagedDepartments = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredDepartments.value.slice(start, end);
});

// 将科室数据按行分组（每行4个）
const buttonRows = computed(() => {
  const rows = [];
  const items = [...pagedDepartments.value];

  while (items.length > 0) {
    rows.push(items.splice(0, 4));
  }

  return rows;
});

const selectDepartment = (department) => {
  if (department.doctorCount === 0) {
    ElMessage.warning("该科室今日暂无医生排班");
    return;
  }  

  emit('department-selected', {
    id: department.department_id,
    name: department.department_name
  });
};

const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置到第一页
};

onMounted(() => {
  fetchScheduleData();  
});
</script>

<style lang="scss" scoped>
.department-selection {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;

  h2 {
    margin: 0;
    color: #303133;
    font-size: 28px;
    font-weight: 600;
  }
}

.search-box {
  width: 100%;
  margin-bottom: 20px;
  display: flex;

  :deep(.el-input) {
    width: 100%;
    max-width: 500px;
    display: block;

    .el-input__wrapper {
      border-radius: 12px;
      padding: 8px 16px;
    }
  }
}

.date-info {
  margin-bottom: 20px;

  .el-tag {
    padding: 8px 16px;
    font-size: 14px;

    .el-icon {
      margin-right: 4px;
    }
  }
}

.loading-container {
  margin: 40px 0;
}

.empty-state {
  margin: 60px 0;
}

.department-buttons {
  margin-bottom: 24px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.button-row {
  display: flex;
  justify-content: flex-start;
  gap: 20px;
  margin-bottom: 20px;
  width: 100%;

  &:last-child {
    margin-bottom: 0;
  }
}

.department-button {
  width: calc(25% - 15px);
  min-width: 250px;
  max-width: 280px;
  height: 140px !important;
  padding: 16px;
  border-radius: 12px;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  flex: 0 0 auto;

  &:hover:not(:disabled) {
    background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
  }

  &:disabled {
    background: linear-gradient(135deg, #9ca3af 0%, #6b7280 100%);
    cursor: not-allowed;
    opacity: 0.6;
  }

  .button-content {
    display: flex;
    align-items: flex-start;
    width: 100%;
    height: 100%;
    color: white;
    text-align: left;
  }

  .button-icon {
    font-size: 36px;
    color: white;
    margin-right: 16px;
    flex-shrink: 0;
    margin-top: 4px;
  }

  .button-text {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
  }

  .department-name {
    font-size: 20px;
    font-weight: 600;
    color: white;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .department-location {
    font-size: 12px;
    color: rgba(255, 255, 255, 0.8);
    margin-bottom: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .department-status {
    display: flex;
    justify-content: space-between;
    font-size: 13px;
    width: 100%;

    .waiting {
      color: #ffd56a;
    }
  }
}

.pagination-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30px;
  margin-top: 30px;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;

  .page-button {
    min-width: 100px;
    height: 40px;
    font-size: 16px;
    border-radius: 8px;
  }

  .page-indicator {
    color: #606266;
    font-size: 16px;
    min-width: 150px;
    text-align: center;
  }
}

/* 平板设备适配 */
@media (max-width: 1200px) {
  .department-selection {
    max-width: 900px;
  }

  .department-button {
    width: calc(33.333% - 14px);
    min-width: 200px;
    height: 130px !important;

    .button-icon {
      font-size: 32px;
    }

    .department-name {
      font-size: 18px;
    }
  }
}

@media (max-width: 992px) {
  .department-selection {
    padding: 18px;
    max-width: 800px;
  }

  .page-header {
    h2 {
      font-size: 24px;
    }
  }

  .button-row {
    gap: 15px;
  }

  .department-button {
    width: calc(33.333% - 10px);
    min-width: 180px;
    height: 120px !important;

    .button-icon {
      font-size: 28px;
      margin-right: 12px;
    }

    .department-name {
      font-size: 16px;
    }

    .department-status {
      font-size: 12px;
    }
  }
}

/* 移动设备适配 */
@media (max-width: 768px) {
  .department-selection {
    padding: 16px;
    max-width: 100%;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    margin-bottom: 20px;

    h2 {
      font-size: 22px;
    }
  }

  .search-box {
    margin-bottom: 20px;

    :deep(.el-input) {
      width: 100%;
      max-width: 600px;
      margin: 0;
      display: block;

      .el-input__wrapper {
        border-radius: 12px;
        padding: 8px 16px;
      }
    }
  }

  .button-row {
    flex-wrap: wrap;
    gap: 12px;
    margin-bottom: 12px;
    justify-content: flex-start;
  }

  .department-button {
    width: calc(50% - 6px);
    flex: 0 0 calc(50% - 6px);
    min-width: unset;
    max-width: calc(50% - 6px);
    height: 120px !important;
    padding: 12px;

    .button-icon {
      font-size: 24px;
      margin-right: 10px;
    }

    .department-name {
      font-size: 16px;
    }

    .department-status {
      font-size: 11px;
      flex-direction: column;
      gap: 4px;
    }
  }

  .pagination-controls {
    flex-direction: column;
    gap: 12px;

    .page-button {
      width: 100%;
      max-width: 200px;
      height: 40px;
    }
  }
}

/* 小屏幕手机适配 */
@media (max-width: 480px) {
  .department-selection {
    padding: 12px;
  }

  .page-header {
    h2 {
      font-size: 20px;
    }
  }

  .button-row {
    gap: 8px;
    justify-content: flex-start;
  }

  .department-button {
    flex: 0 0 calc(50% - 4px);
    max-width: calc(50% - 4px);
    height: 110px !important;
    padding: 10px;

    .button-icon {
      font-size: 20px;
      margin-right: 8px;
    }

    .department-name {
      font-size: 14px;
    }

    .department-status {
      font-size: 10px;
    }
  }
}
</style>